// ==UserScript==
// @name         京东自动价格抓取脚本
// @namespace    http://tampermonkey.net/
// @version      1.1
// @description  自动从京东搜索商品并提交价格数据
// @author       儒释道
// @match        https://dr.jd.com/*
// @grant        GM_xmlhttpRequest
// @grant        GM_addStyle
// @connect      192.168.31.76
// ==/UserScript==

(function() {
    'use strict';

    let isRunning = false;
    let intervalTime = 5000; // 默认5秒间隔
    let timer = null;

    // 添加简单的控制面板
    const panelHTML = `
        <div id="autoPricePanel">
            <label>v1.1间隔时间(ms): <input type="number" id="intervalInput" value="5000"></label>
            <button id="startBtn">启动</button>
            <button id="stopBtn">停止</button>
        </div>
    `;
    document.body.insertAdjacentHTML('beforeend', panelHTML);

    GM_addStyle(`
        #autoPricePanel {
            position: fixed;
            top: 50px;
            right: 20px;
            background-color: #fff;
            padding: 10px;
            border: 1px solid #ccc;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            z-index: 9999;
        }
        #autoPricePanel button {
            margin-left: 5px;
        }
    `);

    document.getElementById('startBtn').addEventListener('click', function() {
        intervalTime = parseInt(document.getElementById('intervalInput').value);
        if (!isRunning) {
            isRunning = true;
            timer = setInterval(fetchAndSearch, intervalTime);
            console.log('✅ 脚本已启动');
        }
    });

    document.getElementById('stopBtn').addEventListener('click', function() {
        if (isRunning) {
            clearInterval(timer);
            isRunning = false;
            console.log('🛑 脚本已停止');
        }
    });

    function fetchAndSearch() {
        GM_xmlhttpRequest({
            method: "GET",
            url: "http://192.168.31.76:5000/get_empty_prices",
            onload: function(response) {
                const data = JSON.parse(response.responseText);
                if (data.code === 200) {
                    performSearch(data.id, data.search_term);
                } else if (data.code === 201) {
                    console.log('📦 已无数据，脚本停止');
                    clearInterval(timer);
                    isRunning = false;
                }
            }
        });
    }

    function performSearch(id, searchTerm) {
        const inputXPath = "/html/body/div[1]/div/div[2]/div[2]/div/div/div/div/div/div/div[2]/div/div/input";
        const inputElement = document.evaluate(inputXPath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

        if (inputElement) {
            inputElement.focus();
            const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
            nativeInputValueSetter.call(inputElement, searchTerm);
            inputElement.dispatchEvent(new Event('input', { bubbles: true }));

            // 添加延时执行搜索和数据提取
            setTimeout(() => {
                document.querySelector('#ui-search button')?.click();
                setTimeout(() => extractData(id, searchTerm), intervalTime);
            }, 500);
        }
    }

    function extractData(id, searchTerm) {
        // 检查是否出现"空空如也"的提示
        const emptyPlaceholder = document.querySelector('.ant-table-placeholder');
        if (emptyPlaceholder && emptyPlaceholder.textContent.includes('空空如也')) {
            console.log(`❌ 搜索结果为空，脚本停止：ID=${id}`);
            // 停止定时器并重置运行状态
            clearInterval(timer);
            isRunning = false;
            return;
        }
        
        // 检查是否出现"商品数据走丢"的提示
        const errorTip = document.querySelector('.pop_tip.fail .tip_ct');
        if (errorTip && errorTip.textContent.includes('商品数据走丢了')) {
            console.log(`❌ 商品数据走丢，脚本停止：ID=${id}`);
            // 停止定时器并重置运行状态
            clearInterval(timer);
            isRunning = false;
            return;
        }
        
        // 提取搜索词中的非中文部分
        const nonChinesePattern = searchTerm.match(/[^\u4e00-\u9fa5]+/g);
        const searchNumber = nonChinesePattern ? nonChinesePattern.join('').trim() : '';
        
        const rows = document.querySelectorAll('.ant-table-body tr.ant-table-row');
        const excludeShops = ['海外', '代购'];
        const priorityShops = ['Under Armour京东自营官方旗舰店','耐克（NIKE）官方旗舰店', 'TOPSPORTS官方旗舰店', 'PUMA官方旗舰店', '耐克（NIKE）京东自营旗舰店', 'INTERSPORT官方旗舰店', 'Under Armour官方旗舰店', 'YYsports旗舰店', '胜道运动旗舰店', 'Adidas京东自营旗舰店'];
        
        let selectedRow = null;

        for (let row of rows) {
            const goodsTitle = row.querySelector('.goods-title')?.textContent.trim() || '';
            const shopName = row.querySelector('.goods-shop')?.textContent.trim();
            const price = row.querySelectorAll('td')[1]?.textContent.trim().replace('¥', '');
            const dataRowKey = row.getAttribute('data-row-key');

            // 只用数字部分匹配标题
            if (searchNumber && !goodsTitle.includes(searchNumber)) continue;
            
            if (excludeShops.some(keyword => shopName.includes(keyword))) continue;

            if (priorityShops.includes(shopName)) {
                selectedRow = { price, dataRowKey };
                break;
            }

            if (!selectedRow) {
                selectedRow = { price, dataRowKey };
            }
        }

        if (selectedRow) {
            const { price, dataRowKey } = selectedRow;
            GM_xmlhttpRequest({
                method: "GET",
                url: `http://192.168.31.76:5000/update_price?id=${id}&price=${price}&key=${dataRowKey}`,
                onload: function() {
                    console.log(`✅ 数据已提交：ID=${id}, 价格=${price}, 键=${dataRowKey}`);
                }
            });
        } else {
            GM_xmlhttpRequest({
                method: "GET",
                url: `http://192.168.31.76:5000/update_price?id=${id}&price=无数据&key=无数据`,
                onload: function() {
                    console.log(`❌ 未找到匹配商品，已提交无数据：ID=${id}`);
                }
            });
        }
    }
})();
